var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
const { createResponse } = require("./utils/responseHelper");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
const articleRouter = require("./routes/article");
const routerRouter = require("./routes/menuManage");
const serviceRouter = require("./routes/service"); 
const verifyToken = require("./utils/verifyToken");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 添加这行来服务上传的文件
app.use("/uploads", express.static(path.join(__dirname, "public/uploads")));

// 跨域
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Content-Type", "application/json;charset=utf-8");

  if (req.method === "OPTIONS") {
    res.status(200).send();
  } else {
    next();
  }
});

// 公开路由
app.use("/", indexRouter);
app.use("/users", usersRouter);

// 应用 verifyToken 中间件到所有需要保护的路由
// app.use(verifyToken);

// 受保护的路由
app.use("/articles", articleRouter);
app.use("/menuManage", routerRouter);
app.use("/customerService", serviceRouter); 

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.stack);

  if (err.status === 404) {
    return createResponse(res, "NOT_FOUND", null, "Resource not found");
  }

  // 对于其他错误，使用通用的服务器错误响应
  createResponse(res, "SERVER_ERROR", null, "An unexpected error occurred");
});

module.exports = app;